const { Service } = require('egg');
const { encodeInp } = require('../utils/encryption');


module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookieVPN() {
    try {
      const { ctx } = this;
      const { sid, pwd } = ctx.data;

      /* * 0. 请求门户主页获取jsessionid */
      const index_url = 'https://vpn.hufe.edu.cn/http/77726476706e69737468656265737421e5f60f9432366d1e7b0c9ce29b5b/sso/login?service=http://i.hufe.edu.cn/user/simpleSSOLogin';
      const index_res = await ctx.curl(index_url, {
        method: 'GET',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
      });
      const setCookie = index_res.headers['set-cookie'] ? index_res.headers['set-cookie'].map(e => e.split(';')[0])[0] : '';
      const jsessionid = (index_res.data.toString().match(/jsessionid=(\w+)?/) || [ '', '' ])[1];

      if (index_res.status === 502) return { setCookie: '', status: 502 };
      console.log('setCookie', setCookie);
      /* end */

      /* * 1. 登录信息门户 */
      const login_url = `https://vpn.hufe.edu.cn/http/77726476706e69737468656265737421e5f60f9432366d1e7b0c9ce29b5b/sso/login;jsessionid=${jsessionid}?service=http://i.hufe.edu.cn/user/simpleSSOLogin`;
      const login_res = await ctx.curl(login_url, {
        method: 'POST',
        headers: {
          Cookie: setCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
        data: {
          username: '202105030113',
          password: encodeInp('hufe@042020'),
          validateCode: '',
          lt: 'e1s1',
          _eventId: 'submit',
        },
      });
      console.log('2', login_res.status, login_res.headers.location);
      /* end */

      /* * 2. 重定向教务登录主页 */
      const RedirectRes1 = await ctx.curl(`${ctx.state.baseUrl}/jsxsd`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
        followRedirect: true, // 允许重定向，模拟登录成功的关键操作
      });
      console.log('3', RedirectRes1.status);

      /* * 3.教务登录 */
      const login_res2 = await ctx.curl(`${ctx.state.baseUrl}/jsxsd/xk/LoginToXk`, {
        method: 'POST',
        headers: {
          Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
        data: {
          encoded: encodeInp(sid) + '%%%' + encodeInp(pwd),
        },
      });
      console.log('4', login_res2.status, login_res2.headers.location);
      /* end */
      if (login_res2.status === 302 && login_res2.headers.location.includes('xsMain.jsp')) return { setCookie, status: 302 };
      else if (login_res2.status === 302 && !login_res2.headers.location.includes('xsMain.jsp')) return { setCookie, status: 500 };

      return { setCookie, status: 200 };

    } catch (err) {
      console.log(err);
      return { setCookie: '', status: 500 };
    }
  }

  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this;
      const { sid, pwd } = ctx.data;
      const encoded = encodeInp(sid) + '%%%' + encodeInp(pwd);
      const apiUrl = `${ctx.state.baseUrl}/jsxsd/xk/LoginToXk`;

      const res = await ctx.curl(apiUrl, {
        method: 'POST',
        data: {
          encoded,
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        timeout: 10000,
      });
      const setCookie = res.headers['set-cookie'] ? res.headers['set-cookie'].map(e => e.split(';')[0]).join(';') : '';
      return { setCookie, status: res.status };

    } catch (err) {
      console.log(err);
      return { setCookie: '', status: 500 };
    }
  }
};
